import { Ref, computed, ref, watch } from 'vue'

interface IProps {
  autoFitHeight: boolean
  setTableHeight: boolean
  height: Ref<number | string | undefined>
}

export function useTableProps(props: IProps) {
  const containerRef = ref<HTMLDivElement>()
  const tableExtraRef = ref<HTMLDivElement>()
  const paginationRef = ref<HTMLDivElement>()

  const tableBox = ref<HTMLDivElement>()

  const tableRealHeight = ref<number | string>()
  /**
   * 特殊处理后的属性集合
   */
  const normalizedTableProps = computed(() => {
    return {
      ...props,
      height: tableRealHeight.value
    }
  })

  watch(props.height, doHeight)

  function doHeight() {
    /**
     * 优先使用 传入的height 属性
     * 依次 auto-fit => setTableHeight 降级
     */
    if (props.height.value) {
      tableRealHeight.value = props.height.value
    }

    if (props.autoFitHeight) {
      let height = containerRef.value?.clientHeight || 0

      if (!height) return 0

      if (tableExtraRef.value) {
        height -= tableExtraRef.value.offsetHeight
      }

      if (paginationRef.value) {
        height -= paginationRef.value.clientHeight
      }
      tableRealHeight.value = height
    }

    // 兼容处理,这里优先判断
    if (props.setTableHeight) {
      tableRealHeight.value = tableBox.value?.clientHeight
        ? tableBox.value.clientHeight - 32
        : 0
    }
  }

  return {
    doHeight,
    containerRef,
    tableExtraRef,
    tableBox,
    paginationRef,
    normalizedTableProps
  }
}
